var express = require('express');
const fs = require('fs');
const XLSX = require('xlsx');
var app = express();

app.get('/', function (req, res) {
   fs.readFile("./rank.html", "utf8", (err, file) => {
    if (err) res.end("err!");
    res.write(file);
    res.end();
  });
})

function savaExcel(data){
  //这个函数是将数据保存为excel
  let arr = data;  
  let raw = [['店铺名','类目','标题','链接','价格','发货地','付款人数','旺旺id']];
  //存放新的数据
  for (let i = 0; i < arr.itemsArray.length; i++) {
      let detail_url = arr.itemsArray[i].auctionURL.replace('//', 'http://');//链接不全我替换一下。
      let detail_title = arr.itemsArray[i].title.replace(/[^\u4E00-\u9FA5]/g,'');//将所有英文字符替换为空字符
      raw[i+1] = [arr.itemsArray[i].shopInfo.title, arr.itemsArray[i].leafCategory, detail_title,detail_url, arr.itemsArray[i].priceShow.price, arr.itemsArray[i].procity, arr.itemsArray[i].realSales, arr.itemsArray[i].nick];
  }
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.aoa_to_sheet(raw);//需要的就是一个数组，我们已经拿到了数组，直接丢给他就可以了
  XLSX.utils.book_append_sheet(workbook,worksheet,'sheet1');

  const filename = `第${arr.mainInfo.page}页.xlsx`;//文件名

  XLSX.writeFile(workbook,filename);
  console.log(`File ${filename} is written successfully `);
};

app.use(express.json({limit: "1mb", extended: true}));//这里需要设置最大请求量！！！
app.post('/api/save', function(req, res) {
  console.log("处理业务逻辑中");
  if(req.body!=="undefined"){
    savaExcel(req.body);
    res.send('保存成功');
  }
});

app.listen(8081, function () {
  console.log("应用实例，访问地址为 http://127.0.0.1:8081");
})